package com.prj.ufdm.demo.tutorial.zkcurator;

import java.util.ArrayList;
import java.util.List;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooDefs.Perms;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;

public class Connect {
	
	public static void main(String[] args) {
		getConnect();
	}
	
	private static CuratorFramework getConnect() {
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
		CuratorFramework client = //CuratorFrameworkFactory.newClient(connectString, retryPolicy);
								 CuratorFrameworkFactory.builder()
					                .connectString("47.98.183.17:2181")
					                .retryPolicy(retryPolicy)
					                .sessionTimeoutMs(6000)
					                .connectionTimeoutMs(3000)
					                .namespace("demo")
					                .build();
		client.start();
        
        return client;
	}
	
	private static CuratorFramework aclClient(){
		 
        //默认创建的根节点是没有做权限控制的--需要自己手动加权限???----
        ACLProvider aclProvider = new ACLProvider() {
            private List<ACL> acl ;
            @Override
            public List<ACL> getDefaultAcl() {
                if(acl ==null){
                    ArrayList<ACL> acl = ZooDefs.Ids.CREATOR_ALL_ACL;
                    acl.clear();
                    acl.add(new ACL(Perms.ALL, new Id("auth", "admin:admin") ));
                    this.acl = acl;
                }
                return acl;
            }
            @Override
            public List<ACL> getAclForPath(String path) {
                return acl;
            }
        };
        String scheme = "digest";
        byte[] auth = "admin:admin".getBytes();
        int connectionTimeoutMs = 5000;
        String connectString = "10.125.2.44:2181";
        String namespace = "testnamespace";
        CuratorFramework client = CuratorFrameworkFactory.builder().aclProvider(aclProvider).
        authorization(scheme, auth).
        connectionTimeoutMs(connectionTimeoutMs).
        connectString(connectString).
        namespace(namespace).
        retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000)).build();
        client.start();
        return client;
    }
}
